<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import type { FormInstance, TableColumnsType } from 'ant-design-vue';
// 按照规则第8条，不导入message，直接使用window.$message
// 移除类型导入，使用项目全局类型
import { createParameter, deleteParameter, fetchAllParameters, updateParameter } from '@/service/api';

// 表单引用
const formRef = ref<FormInstance>();

// 数据状态
const loading = ref(false);
const tableData = ref<any[]>([]);

// 模态框状态
const modalVisible = ref(false);
const modalTitle = ref('新增参数');
const isEdit = ref(false);

// 筛选条件
const filters = reactive({
  modelId: undefined as number | undefined,
  fieldName: undefined as string | undefined,
  parameterType: undefined as string | undefined,
  showRequired: false,
  showOptional: false
});

// 表单数据
const formData = reactive<any>({
  name: '',
  fieldName: '',
  type: undefined,
  modelId: undefined,
  defaultValue: '',
  description: '',
  required: false,
  status: 1
});

// 参数类型选项
const parameterTypeOptions = [
  { label: '字符串', value: 'STRING' },
  { label: '整数', value: 'INTEGER' },
  { label: '小数', value: 'DECIMAL' },
  { label: '布尔值', value: 'BOOLEAN' },
  { label: '日期', value: 'DATE' },
  { label: '时间', value: 'DATETIME' },
  { label: 'JSON', value: 'JSON' }
];

// 表格列定义
const columns: TableColumnsType = [
  {
    title: '参数名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '字段名',
    dataIndex: 'fieldName',
    key: 'fieldName',
    width: 120
  },
  {
    title: '参数类型',
    dataIndex: 'type',
    key: 'type',
    width: 100
  },
  {
    title: '默认值',
    dataIndex: 'defaultValue',
    key: 'defaultValue',
    width: 120,
    ellipsis: true
  },
  {
    title: '必填',
    dataIndex: 'required',
    key: 'required',
    width: 80
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
];

// 加载参数列表
async function loadParameters() {
  try {
    loading.value = true;
    const response = await fetchAllParameters();

    if (response.data) {
      tableData.value = Array.isArray(response.data) ? response.data : [];
    }
  } catch (error) {
    console.error('加载参数列表失败:', error);
    window.$message?.error('加载参数列表失败');
  } finally {
    loading.value = false;
  }
}

// 打开新增模态框
function openAddModal() {
  modalTitle.value = '新增参数';
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
}

// 打开编辑模态框
function openEditModal(record: any) {
  modalTitle.value = '编辑参数';
  isEdit.value = true;
  Object.assign(formData, record);
  modalVisible.value = true;
}

// 重置表单
function resetForm() {
  Object.assign(formData, {
    name: '',
    fieldName: '',
    type: undefined,
    modelId: undefined,
    defaultValue: '',
    description: '',
    required: false,
    status: 1
  });
  formRef.value?.resetFields();
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value?.validate();

    loading.value = true;

    if (isEdit.value) {
      await updateParameter(formData.id!, formData as Api.Valuation.Parameter);
      window.$message?.success('更新参数成功');
    } else {
      await createParameter(formData as Api.Valuation.Parameter);
      window.$message?.success('创建参数成功');
    }

    modalVisible.value = false;
    await loadParameters();
  } catch (error) {
    console.error('提交失败:', error);
    window.$message?.error('操作失败');
  } finally {
    loading.value = false;
  }
}

// 删除参数
async function handleDelete(id: number) {
  try {
    loading.value = true;
    await deleteParameter(id);
    window.$message?.success('删除参数成功');
    await loadParameters();
  } catch (error) {
    console.error('删除失败:', error);
    window.$message?.error('删除失败');
  } finally {
    loading.value = false;
  }
}

// 启用参数
function handleEnable(id: number) {
  console.log('启用参数ID:', id);
  window.$message?.info('启用功能待实现');
}

// 筛选变化处理
function handleFilterChange() {
  loadParameters();
}

// 重置筛选
function resetFilters() {
  Object.assign(filters, {
    modelId: undefined,
    fieldName: undefined,
    parameterType: undefined,
    showRequired: false,
    showOptional: false
  });
  loadParameters();
}

// 必填/可选切换
function handleRequiredToggle(type: 'required' | 'optional') {
  if (type === 'required') {
    filters.showRequired = !filters.showRequired;
    filters.showOptional = false;
  } else {
    filters.showOptional = !filters.showOptional;
    filters.showRequired = false;
  }
  loadParameters();
}

onMounted(() => {
  loadParameters();
});
</script>

<template>
  <div class="parameter-management">
    <ACard>
      <template #title>
        <div class="flex items-center justify-between">
          <span>参数管理</span>
          <AButton type="primary" @click="openAddModal">
            <icon-carbon:add class="mr-1" />
            新增参数
          </AButton>
        </div>
      </template>

      <!-- 筛选条件 -->
      <AForm class="mb-4" layout="inline">
        <AFormItem label="模型ID">
          <AInputNumber
            v-model:value="filters.modelId"
            placeholder="输入模型ID"
            class="w-full"
            @change="handleFilterChange"
          />
        </AFormItem>
        <AFormItem label="字段名">
          <AInput v-model:value="filters.fieldName" placeholder="输入字段名" allow-clear @change="handleFilterChange" />
        </AFormItem>
        <AFormItem label="参数类型">
          <ASelect
            v-model:value="filters.parameterType"
            placeholder="选择参数类型"
            :options="parameterTypeOptions"
            allow-clear
            class="min-w-[150px]"
            @change="handleFilterChange"
          />
        </AFormItem>
        <AFormItem label="筛选选项">
          <ASpace :size="2">
            <AButton :type="filters.showRequired ? 'primary' : 'default'" @click="handleRequiredToggle('required')">
              必填参数
            </AButton>
            <AButton :type="filters.showOptional ? 'primary' : 'default'" @click="handleRequiredToggle('optional')">
              可选参数
            </AButton>
          </ASpace>
        </AFormItem>
        <AFormItem>
          <AButton type="primary" ghost @click="resetFilters">
            <template #icon>
              <icon-carbon:update-now class="mr-1" />
            </template>
            重置筛选
          </AButton>
        </AFormItem>
      </AForm>

      <ATable :columns="columns" :data-source="tableData" :loading="loading" row-key="id" :scroll="{ x: 1000 }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'required'">
            <ATag :color="record.required ? 'red' : 'blue'">
              {{ record.required ? '必填' : '可选' }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'status'">
            <ATag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'action'">
            <ASpace>
              <AButton size="small" @click="openEditModal(record)">编辑</AButton>
              <AButton v-if="record.status !== 1" size="small" type="primary" @click="handleEnable(record.id)">
                启用
              </AButton>
              <APopconfirm title="确定要删除这个参数吗？" @confirm="handleDelete(record.id)">
                <AButton size="small" danger>删除</AButton>
              </APopconfirm>
            </ASpace>
          </template>
        </template>
      </ATable>
    </ACard>

    <!-- 新增/编辑模态框 -->
    <AModal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="loading"
      width="700px"
      @ok="handleSubmit"
      @cancel="modalVisible = false"
    >
      <AForm ref="formRef" :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <AFormItem label="参数名称" name="name" :rules="[{ required: true, message: '请输入参数名称' }]">
          <AInput v-model:value="formData.name" placeholder="请输入参数名称" />
        </AFormItem>

        <AFormItem label="参数类型" name="type" :rules="[{ required: true, message: '请选择参数类型' }]">
          <ASelect v-model:value="formData.type" placeholder="请选择参数类型" :options="parameterTypeOptions" />
        </AFormItem>

        <AFormItem label="模型ID" name="modelId" :rules="[{ required: true, message: '请输入模型ID' }]">
          <AInputNumber v-model:value="formData.modelId" placeholder="请输入模型ID" class="w-full" />
        </AFormItem>

        <AFormItem label="字段名" name="fieldName" :rules="[{ required: true, message: '请输入字段名' }]">
          <AInput v-model:value="formData.fieldName" placeholder="请输入字段名" />
        </AFormItem>

        <AFormItem label="默认值" name="defaultValue">
          <AInput v-model:value="formData.defaultValue" placeholder="请输入默认值" />
        </AFormItem>

        <AFormItem label="必填" name="required">
          <ASwitch v-model:checked="formData.required" />
        </AFormItem>

        <AFormItem label="描述" name="description">
          <ATextarea v-model:value="formData.description" placeholder="请输入参数描述" :rows="3" />
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<style scoped>
.parameter-management {
  padding: 24px;
}

/* .filter-section {
  padding: 16px;
  background: var(--ant-fill-tertiary);
  border-radius: 6px;
  border: 1px solid var(--ant-border-color-split);
} */

/* 暗色主题下的样式 */
/* .dark .filter-section {
  background: #2a2a2a;
  border: 1px solid #404040;
} */

@media (max-width: 768px) {
  .parameter-management {
    padding: 16px;
  }

  .filter-section .grid {
    grid-template-columns: 1fr;
  }
}
</style>
